package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.exception.DishEnableFailedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetMealDishMapper;
import com.sky.mapper.SetMealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import com.sky.vo.SetmealVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class DishServiceImpl implements DishService {
    //    注入dao层
    @Autowired
    DishMapper dishMapper;
    @Autowired
    DishFlavorMapper dishFlavorMapper;
    @Autowired
    SetMealDishMapper setMealDishMapper;
    @Autowired
    SetMealMapper setMealMapper;

    /**
     * 新增菜品操作
     *
     * @param dishDTO
     * @return
     */
    @Transactional
    public void save(DishDTO dishDTO) {

//        创建dish类型，进行属性的拷贝
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.upload(dish);
//        获取insert生成的菜品的id
        Long dishId = dish.getId();
//
        //        获取口味
        List<DishFlavor> flavors = dishDTO.getFlavors();
//        判断
        if (flavors != null && flavors.size() > 0) {
            flavors.forEach(item -> {
                item.setDishId(dishId);
            });
//            插入口味数据
            dishFlavorMapper.insert(flavors);
        }
    }

    /**
     * 菜品的分页查询操作
     *
     * @param pageQueryDTO
     * @return
     */
    @Override
    public PageResult page(DishPageQueryDTO pageQueryDTO) {
//        这是sql语句后面的那个limit语句拼接
        PageHelper.startPage(pageQueryDTO.getPage(), pageQueryDTO.getPageSize());
        Page<DishVO> dishVO = dishMapper.page(pageQueryDTO);
        return new PageResult(dishVO.getTotal(), dishVO.getResult());
    }

    /**
     * 菜品的批量删除的操作
     *
     * @param ids
     * @return
     */
    @Override
    public void delete(List<Long> ids) {
//        判断菜品是否可以删除
//        1.启售不可删除
        for (Long id : ids) {
            Dish dish = dishMapper.selectById(id);
            if (Objects.equals(dish.getStatus(), StatusConstant.ENABLE)) {
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }
//        2.菜品与套餐关联不可删除
        List<Long> MealIds = setMealDishMapper.selectById(ids);
        if (MealIds != null && MealIds.size() > 0) {
            for (Long mealId : MealIds) {
                SetmealVO setmealVO = setMealMapper.selectByID(mealId);
                String name = setmealVO.getName();
                throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL+"，套餐为："+name);
            }

        }

//        可以删除
        for (Long id : ids) {

            dishMapper.deleteById(id);
            //删除菜品关联的口味
            dishFlavorMapper.deleteById(id);
        }

    }

    /**
     * 根据id查询后启用禁用菜品
     *
     * @param status
     * @param id
     * @return
     */
    @Override
    public void startOrBin(Integer status, Long id) {
        ArrayList<Long> dishId = new ArrayList<>();
        dishId.add(id);
//        停售需要判断套餐是否停售
        List<Long> setMealIds = setMealDishMapper.selectById(dishId);
//        存在就进行查，不然就可以直接改了
        if (setMealIds != null && setMealIds.size() > 0){
            for (Long setMealId : setMealIds) {
                SetmealVO setmealVO = setMealMapper.selectByID(setMealId);
//                说明套餐还在起售，那么与套餐相关的菜品就不可以停售
               if (setmealVO.getStatus() == 1){
//                   获取套餐的名字，便于查找
                   String name = setmealVO.getName();
                   throw new DishEnableFailedException("套餐："+ name +"->"+ MessageConstant.DISH_ENABLE_FAILED);
               }
            }
        }
        Dish dish = dishMapper.selectById(id);
        dish.setStatus(status);
        dishMapper.update(dish);
    }

    /**
     * 根据id查询，用于数据回显
     *
     * @param id
     * @return
     */
    @Override
    public DishVO selectById(Long id) {
//        获取到dish对象为DishVo对象进行拷贝
        Dish dish = dishMapper.selectById(id);
//        根据dish的id进行数据的查询，获得相应的口味
        List<DishFlavor> dishFlavors = dishFlavorMapper.selectById(id);
//        创建DishVo对象进行数据的拷贝
        DishVO dishVO = new DishVO();
//        使用Bean的工具进行拷贝
        BeanUtils.copyProperties(dish,dishVO);
//        单独设置口味
        dishVO.setFlavors(dishFlavors);
//        弄完后，private String categoryName 是空的
        return dishVO;
    }

    /**
     * 修改菜品信息
     * @return
     */
    public void edi(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dishMapper.update(dish);
        Long dishId = dishDTO.getId();
//        将原来的口味从数据库删除
        dishFlavorMapper.deleteById(dishId);
//        获取填写的新口味
        List<DishFlavor> dishFlavors = dishDTO.getFlavors();
//        判断是否需要进行插入
        if (dishFlavors != null && dishFlavors.size() >0){
            for (DishFlavor dishFlavor : dishFlavors) {
//                口味跟口味的值前端给的，但是菜品的id前端没有的，需要后端获取然后设置的
                dishFlavor.setDishId(dishId);
            }
//            进行口味的添加
            dishFlavorMapper.insert(dishFlavors);
        }
    }

    /**
     * 根据分类id查询菜品
     * @param categoryId
     * @return
     */
    @Override
    public List<Dish> selectByCategoryId(Long categoryId) {
        return dishMapper.selectByCategoryId(categoryId);
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {

        List<Dish> dishList = dishMapper.selectByCategoryIdWithStatus(dish);
        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.selectById(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }

}
